﻿using DeviceMonitor.Classes;
using DeviceMonitor.Dao;
using DeviceMonitor.Model;
using DeviceMonitor.Utils;
using DeviceMonitor.ViewModel;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WpfApplication1.Classes;
//using System.Data.SQLite;
using MPMS.Srv.WebService;
using System.Windows.Threading;
using System.Web.UI.WebControls;

namespace DeviceMonitor
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        MonitorViewModel viewModel;
        static List<Thread> threadList;
        Thread serviceThread;
        Thread dbServiceThread = null;
        private DispatcherTimer timer;
        private DispatcherTimer timer2;

        public MainWindow()
        {
            InitializeComponent();
            viewModel = new MonitorViewModel();
            this.DataContext = viewModel;

            threadList = new List<Thread>();
            
            this.frmMain.Navigate(new Uri("Pages/MonitorPage.xaml", UriKind.Relative));

            this.Loaded += MainWindow_Loaded;
            this.Closed += MainWindow_UnLoaded;

           string code = App.GetConfig().UploadManually;
            if(code == "0")
            {
                UploadManually.Visibility = Visibility.Collapsed;
            }
            App.MainWindow = this;
        }
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //serviceThread = new Thread(MainWindow.StartCanbusService);
            //serviceThread.Start();
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMinutes(App.GetConfig().timerUploadBillSeconds);
            timer.Tick += new EventHandler(timeCycle1);
            timer.Start();

            timer2 = new DispatcherTimer();
            timer2.Interval = TimeSpan.FromHours(App.GetConfig().timerUploadAlermHours);
            timer2.Tick += new EventHandler(timeCycle2);
            timer2.Start();

            string uploadBill = App.GetConfig().uploadBill;
            if ("1".Equals(uploadBill))
            {
                DoUploadBill();
            }

            string uploadAlarm = App.GetConfig().uploadAlarm;
            if ("1".Equals(uploadAlarm))
            {
                DoUploadAlarm();
            }
            

        }

      

        private void timeCycle1(object sender, EventArgs e)
        {
            string uploadBill = App.GetConfig().uploadBill;
            if ("1".Equals(uploadBill))
            {
                DoUploadBill();
            }

        }

        private void timeCycle2(object sender, EventArgs e)
        {
            string uploadAlarm = App.GetConfig().uploadAlarm;
            if ("1".Equals(uploadAlarm))
            {
                DoUploadAlarm();
            }
        }

       
        public static void StartCanbusService()
        {
            List<CanBusNet> canBusNets = App.GetCanBusNetList();
            int index = 0;
            foreach (CanBusNet canBus in canBusNets)
            {
                canBus.StartService();

                //Thread newThread = new Thread(MainWindow.DoSendMessage);
                //newThread.Start(index);
                //threadList.Add(newThread);

                index++;
            }
            Thread newThread = new Thread(MainWindow.DoSendMessage);
            newThread.Start(index);
            threadList.Add(newThread);
        }
        public static void DoSendMessage(Object index)
        {
            //int idx = (int)index;
            Boolean done = App.stopCanbusThread;
            string sendMessage = App.GetConfig().sendMessage;
            while (!done && "true".Equals(sendMessage))
            {
                for (int idx = 0; idx < (int)index; idx++)
                {
                    if (App.stopCanbusThread) return;
                    List<DeviceModel> devices = App.GetDeviceGroups()[idx].devices;
                    foreach (DeviceModel device in devices)
                    {
                        if (App.stopCanbusThread) return;
                        int devCode = int.Parse(device.code);
                        String cmd = MessageUtils.getTimerCheckMessage(devCode);
                        if (App.GetCanBusNetList()[idx].mTcp.Connected)
                        {
                            LogObject.WriteLog("send message: " + cmd, "Debug");
                            App.GetCanBusNetList()[idx].SendData(cmd, true);
                        }
                        if (App.stopCanbusThread) return;
                        Thread.Sleep(App.GetConfig().timerCheckSeconds);
                        if (App.stopCanbusThread) return;
                    }
                }
            }
        }
        public static void DoUploadBill()
        {
            Boolean done = false;
            while (!done)
            {
                try
                {
                    //查询时间
                    //string endTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    //String lastQueryTime = (String)SqlMapDao.instance().QueryForObject("selectLastQueryTime", null);

                    //JObject paramJSON = new JObject();
                    //paramJSON.Add("lastQueryTime", lastQueryTime);
                    //paramJSON.Add("currentQueryTime", endTime);

                    //Hashtable paraMap = new Hashtable();
                    //paraMap.Add("queryStartDateTime", lastQueryTime);
                    //paraMap.Add("queryEndDateTime", endTime);

                    /*ArrayList bills = (ArrayList)MsSqlMapDao.instance().QueryForList("selectBills", paraMap);

                    if (bills.Count == 0) continue;

                    String id = (String)SqlMapDao.instance().QueryForObject("selectUUID", null);

                    BillModel billModel = new BillModel();
                    billModel.id = id;
                    billModel.beginTime = lastQueryTime;
                    billModel.createTime = endTime;
                    billModel.itemCount = bills.Count.ToString();

                    foreach (BillItemModel item in bills)
                    {
                        String itemId = (String)SqlMapDao.instance().QueryForObject("selectUUID", null);
                        item.id = itemId;
                        item.billId = id;
                    }
                    SqlMapDao.instance().Insert("insertBill", billModel);
                    SqlMapDao.instance().Insert("insertBillItems", bills);

                    SqlMapDao.instance().Update("updateLastQueryTime", endTime);

                    try
                    {
                        DockingInfo dockingInfo = new DockingInfo();
                        foreach (BillItemModel item in bills)
                        {
                            dockingInfo.MediumInfoAsync(
                                item.productNo,
                                item.billNo,
                                item.corpName,
                                item.carNo,
                                item.weightTime,
                                item.product,
                                item.nnum
                            );
                        }
                    }catch(Exception ex)
                    {
                        LogObject.WriteLog(ex.ToString(), "Message");
                    }*/
                    //查询时间
                    string endTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    JObject paramJSON = new JObject();
                    string url = "http://" + App.GetConfig().DBServiceIp + ":" + App.GetConfig().DBServicePort + "/alerm/getUploadTime";
                    String resp = HttpPostHelper.doHttpPost(url, paramJSON.ToString());
                    JObject Json = JObject.Parse(resp);
                    JObject json = (JObject)Json.GetValue("data");
                    String lastQueryTime = (String)json.GetValue("lastQueryTime");
                    //String lastQueryTime = (String)SqlMapDao.instance().QueryForObject("selectLastQueryTime", null);
                    //String response = HttpPostHelper.doHttpGet("/centerBusiness/queryUploadBillNew");
                    String response = HttpPostHelper.doHttpGet("/centerBusiness/queryUploadBill?lastQueryTime=" + lastQueryTime + "&currentQueryTime=" + endTime);

                    JObject respJson = JObject.Parse(response);
                    string status = respJson["code"].ToString();
                    if (status.ToLower() == "200")
                    {
                        JArray detial = (JArray)respJson.GetValue("data");
                        //JObject json = (JObject)respJson.GetValue("data");
                        //JArray detial = (JArray)json.GetValue("dataList"); ;
                        //string lastQueryTime = (string)json.GetValue("lastQueryTime");
                        //string endTime = (string)json.GetValue("currentQueryTime");


                        if (detial.Count > 0)
                        {
                            String id = getUUID();
                            BillModel billModel = new BillModel();
                            billModel.id = id;
                            billModel.beginTime = lastQueryTime;
                            billModel.createTime = endTime;
                            billModel.itemCount = detial.Count.ToString();


                            JObject billJson = new JObject();
                            billJson.Add("id", id);
                            billJson.Add("beginTime", lastQueryTime);
                            billJson.Add("createTime", endTime);
                            billJson.Add("itemCount", detial.Count.ToString());

                            JArray items = new JArray();
                            foreach (JObject jsonItem in detial)
                            {
                                JObject itemJson = new JObject();
                                String itemId = getUUID();

                                itemJson.Add("id", itemId);
                                itemJson.Add("billId", id);
                                itemJson.Add("carNo", (string)jsonItem["carNo"]);
                                itemJson.Add("product", (string)jsonItem["product"]);
                                itemJson.Add("nnum", (string)jsonItem["nnum"]);
                                itemJson.Add("billNo", (string)jsonItem["billNo"]);
                                itemJson.Add("corpName", (string)jsonItem["corpName"]);
                                itemJson.Add("weightTime", (string)jsonItem["weightTime"]);

                                items.Add(itemJson);
                            }

                            JObject json1 = new JObject();
                            json1.Add("items", items);
                            string billUrl = "http://" + App.GetConfig().DBServiceIp + ":" + App.GetConfig().DBServicePort + "/alerm/insertBill";
                            String billResponse = HttpPostHelper.doHttpPost(billUrl, billJson.ToString());
                            string billItemUrl = "http://" + App.GetConfig().DBServiceIp + ":" + App.GetConfig().DBServicePort + "/alerm/insertBillItems";

                            String billItemsResponse = HttpPostHelper.doHttpPost(billItemUrl, json1.ToString());

                            string responseMsg = "";
                            DockingInfo dockingInfo = new DockingInfo();
                            foreach(JObject item in items)
                            {
                                responseMsg = dockingInfo.MediumInfo(
                                      "",
                                      (string)item["billNo"],
                                      "东营齐润化工有限公司",
                                       (string)item["carNo"],
                                     (string)item["weightTime"],
                                      (string)item["product"],
                                      (string)item["nnum"]
                                  );
                                if (responseMsg.Equals("true"))
                                {
                                    JObject uploadTime = new JObject();
                                    uploadTime.Add("currentQueryTime", endTime);
                                    uploadTime.Add("type", "record");
                                    string timeUrl = "http://" + App.GetConfig().DBServiceIp + ":" + App.GetConfig().DBServicePort + "/alerm/updateLastQueryTime";
                                    String uploadResponse = HttpPostHelper.doHttpPost(timeUrl, uploadTime.ToString());


                                }
                            }
                        }
                    }
                    
                }
                catch (Exception ex)
                {
                    LogObject.WriteLog(ex.ToString(), "Message");
                }
                done = true;
                //Thread.Sleep(App.GetConfig().timerUploadBillSeconds * 1000 * 60*60);
            }
        }

        public static void DoUploadAlarm()
        {
            //MessageBox.Show("报警上传");
            AlarmUtils.DoUploadAlarm();
            
        }
        public static void DoUploadBillSqlite()
        {
            Boolean done = false;

            while (!done)
            {
                try
                {
                    //查询时间
                    string endTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    String lastQueryTime = (String)SqlMapDao.instance().QueryForObject("selectLastQueryTime", null);

                    JObject paramJSON = new JObject();
                    paramJSON.Add("beginTime", lastQueryTime);
                    paramJSON.Add("endTime", endTime);
                    paramJSON.Add("limit", "100");

                    String response = HttpPostHelper.doHttpPost("/dbServ/queryBills", paramJSON.ToString());
                    JObject billJsonObj = JObject.Parse(response);
                    JArray bills = (JArray)billJsonObj["records"];

                    String id = (String)SqlMapDao.instance().QueryForObject("selectUUID", null);

                    BillModel billModel = new BillModel();
                    billModel.id = id;
                    billModel.beginTime = lastQueryTime;
                    billModel.createTime = endTime;
                    billModel.itemCount = "0";

                    List<BillItemModel> items = new List<BillItemModel>();
                    foreach(JObject bill in bills)
                    {
                        BillItemModel item = new BillItemModel();
                        String itemId = (String)SqlMapDao.instance().QueryForObject("selectUUID", null);

                        item.id = itemId;
                        item.billId = id;
                        item.carNo = (string)bill["trucksno"];
                        item.product = (string)bill["product"];
                        item.nnum = (string)bill["cjz"];
                        item.billNo = (string)bill["orderno"];
                        item.corpName = (string)bill["customername"];
                        item.weightTime = (string)bill["cmzsj"];

                        items.Add(item);
                    }
                    billModel.itemCount = items.Count.ToString();

                    if (items.Count > 0)
                    {
                        SqlMapDao.instance().Insert("insertBill", billModel);
                        SqlMapDao.instance().Insert("insertBillItems", items);
                    }
                    SqlMapDao.instance().Update("updateLastQueryTime", endTime);
                }
                catch (Exception ex){
                    Console.WriteLine("********************");
                    Console.WriteLine(ex.ToString());
                    Console.WriteLine("********************");
                }
                
                Thread.Sleep(App.GetConfig().timerUploadBillSeconds * 1000 * 60);
            }
        }

        private void MainWindow_UnLoaded(object sender, EventArgs e)
        {
            App.stopCanbusThread = true;

            foreach (Thread thread in threadList)
            {
                if (null != thread)
                {
                    thread.Abort();
                }
            }
            if(null != serviceThread)
            {
                try
                {
                    serviceThread.Abort();
                }
                catch { }
            }
            if (null != dbServiceThread)
            {
                try
                {
                    dbServiceThread.Abort();
                }
                catch { }
            }
        }
        private String currentPageUri = "MonitorPage";
        private void Button_Click_GoMonitorPage(object sender, RoutedEventArgs e)
        {
            App.globalDeviceGroupCode = "01";
            if (currentPageUri.Equals("MonitorPage"))
            {
                this.frmMain.Refresh();
            }
            else
            {
                currentPageUri = "MonitorPage";
                this.frmMain.Navigate(new Uri("Pages/MonitorPage.xaml", UriKind.Relative));
            }
        }
        private void Button_Click_GoMonitorPage02(object sender, RoutedEventArgs e)
        {
            App.globalDeviceGroupCode = "02";
            if (currentPageUri.Equals("MonitorPage"))
            {
                this.frmMain.Refresh();
            }
            else
            {
                currentPageUri = "MonitorPage";
                this.frmMain.Navigate(new Uri("Pages/MonitorPage.xaml", UriKind.Relative));
            }
        }
        private void Button_Click_GoMonitorPage03(object sender, RoutedEventArgs e)
        {
            App.globalDeviceGroupCode = "03";
            if (currentPageUri.Equals("MonitorPage"))
            {
                this.frmMain.Refresh();
            }
            else
            {
                currentPageUri = "MonitorPage";
                this.frmMain.Navigate(new Uri("Pages/MonitorPage.xaml", UriKind.Relative));
            }
        }

        private void Button_Click_GoAlermPage(object sender, RoutedEventArgs e)
        {
            currentPageUri = "AlermPage";
            this.frmMain.Navigate(new Uri("Pages/AlermPage.xaml", UriKind.Relative));
        }
        //
        private void Button_Click_ManualUpload(object sender, RoutedEventArgs e)
        {
            currentPageUri = "AlermPage2new";
            this.frmMain.Navigate(new Uri("Pages/AlermPage2new.xaml", UriKind.Relative));
        }
        private void Button_Click_GoBillPage(object sender, RoutedEventArgs e)
        {
            currentPageUri = "BillPage";
            this.frmMain.Navigate(new Uri("Pages/BillPage.xaml", UriKind.Relative));
        }

        private void Button_Click_GoLoadRecordPage(object sender, RoutedEventArgs e)
        {
            currentPageUri = "LoadRecordPage";
            this.frmMain.Navigate(new Uri("Pages/LoadRecordPage.xaml", UriKind.Relative));
        }

        private void Button_Click_StopAllDevice(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("是否停止所有设备?", "确认", MessageBoxButton.YesNo);
            if (result != MessageBoxResult.Yes)
            {
                return;
            }


        }
        public static String getUUID()
        {
            return System.Guid.NewGuid().ToString().Replace("-", "");
        }

        private void RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            App.globalDeviceGroupCode = "03";
            if (currentPageUri.Equals("MonitorPage"))
            {
                this.frmMain.Refresh();
            }
            else
            {
                currentPageUri = "MonitorPage";
                this.frmMain.Navigate(new Uri("Pages/AlermPage2.xaml", UriKind.Relative));
            }
        }

    }
}
